package com.itwn.controller;


import com.github.pagehelper.PageInfo;
import com.itwn.entity.Order;
import com.itwn.entity.User;
import com.itwn.result.ResponseResult;
import com.itwn.service.OrderService;
import com.itwn.vo.OrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@CrossOrigin
@Api
@RequestMapping("order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @ApiOperation(value = "订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    paramType = "query",name = "orderNo",value = "订单编号",
                    dataType = "String",required = false),
    })
    @GetMapping("/showList")
    public ResponseResult<PageInfo<OrderVo>> showList(String orderNo,
                                                      @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                                      @RequestParam(value = "pageSize",defaultValue = "3")Integer pageSize){
        ResponseResult<PageInfo<OrderVo>> reuslt = new ResponseResult<>();
        PageInfo<OrderVo> pageInfo = orderService.queryAllOrder(orderNo, pageNum, pageSize);
        reuslt.setCode(200);
        reuslt.setMsg("查询成功！");
        reuslt.setData(pageInfo);
        return reuslt;
    }

//    修改订单
    @PostMapping("/modifyOrder")
    public ResponseResult<OrderVo> modifyOrder(OrderVo order){
        ResponseResult<OrderVo> result = new ResponseResult<>();
        String userName = order.getUserName();
        User user = orderService.selectUserByName(userName);
        Integer userId = user.getUserId();
        order.setUserId(userId);
        int i = orderService.modifyOrder(order);
        if(i>0){
            result.setCode(200);
            result.setMsg("更新成功！");
            return result;
        }else {
            result.setCode(101);
            result.setMsg("更新失败！");
            return result;
        }
    }

//    删除订单
    @DeleteMapping("/removeOrder/{orderNo}")
    public ResponseResult<Order> removeOrder(@PathVariable("orderNo") String orderNo){
        ResponseResult<Order> result = new ResponseResult<>();
        try{
//        删除订单表数据
            int i = orderService.removeOrder(orderNo);
//        删除订单明细表数据
            orderService.removeOrderDetail(orderNo);
            if(i>0){
                result.setCode(200);
                result.setMsg("删除成功！");
                return result;
            }else {
                result.setCode(101);
                result.setMsg("删除失败！");
                return result;
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }
}
